//
//  RadioViewController.m
//  News_radio
//
//  Created by lanou on 15/12/16.
//  Copyright © 2015年 lanou3G. All rights reserved.
//

#import "RadioViewController.h"
#import "RadioCollectionViewCell.h"
#import "RadioCollectionReusableView.h"
#import "SingleRadioListTableViewController.h"
#import "PlayRadioTableViewController.h"

#import "RadioListModel.h"
#import "RadioPlay.h"
#import "PlayRadioModel.h"

@interface RadioViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain)UICollectionView *collectionView;

@property (nonatomic, strong)NSMutableArray *allArray;

@property (nonatomic, strong)NSMutableArray *sectionTitleArr;

@property (nonatomic, retain)UIImageView *imageView1;

@property (nonatomic, retain)UIView *view1;


@end

@implementation RadioViewController


// 懒加载
- (NSMutableArray *)allArray {
    if (!_allArray) {
        _allArray = [[NSMutableArray alloc] init];
    }
    return _allArray;
}
- (NSMutableArray *)sectionTitleArr {
    if (!_sectionTitleArr) {
        _sectionTitleArr = [[NSMutableArray alloc] init];
    }
    return _sectionTitleArr;
}


// 解析数据
- (void)setRadioListData {
    
    [LORequestManger GET:kRadioListUrl success:^(id response) {
        
        NSDictionary *rootDic = (NSDictionary *)response;
        for (NSDictionary *dic1 in rootDic[@"cList"]) {
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dic2 in dic1[@"tList"]) {
                RadioListModel *radioListModel = [[RadioListModel alloc] init];
                radioListModel.cid = dic1[@"cid"];
                radioListModel.cname = dic1[@"cname"];
                [radioListModel setValuesForKeysWithDictionary:dic2];
                [array addObject:radioListModel];
            }
            [self.allArray addObject:array];
            [self.sectionTitleArr addObject:dic1[@"cname"]];
        }

        [self.collectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"电台";

    [self setRadioListData];
    
    // 设置 collectionView
    [self setCollectionView];
    
    
    // 如果有电台正在播放，在电台的首页设置一个动画，并且点击该动画可以返回播放页面
    self.view1 = [[UIView alloc] initWithFrame:CGRectMake(kWidth - 30,140, 30, 20)];
    self.view1.backgroundColor = [UIColor colorWithRed:226/255.0 green:62/255.0 blue:67/255.0 alpha:0.98];
    
    self.imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(5,0, 20, 20)];
    NSMutableArray *imageArray = [NSMutableArray array];
    for (int i = 1; i < 27; i ++) {
        NSString *imageName = [NSString stringWithFormat:@"icon_upbar_icon_playing%d.png",i];
        UIImage *image = [UIImage imageNamed:imageName];
        [imageArray addObject:image];
    }
    self.imageView1.animationImages = imageArray;
    self.imageView1.animationDuration = 0.5;
    self.imageView1.animationRepeatCount = 0;
    
    self.imageView1.userInteractionEnabled = YES;
    [self setImageViewWithLayer:self.view1];
    
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(returnPlay)];
    [self.imageView1 addGestureRecognizer:tap];
    
    // Do any additional setup after loading the view.
}

// 设置为圆角
- (void)setImageViewWithLayer:(UIView *)imageView {
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = imageView.bounds.size.height / 6;
}


// 在页面将要出现的时候判断当前时候为播放状态，如果是播放状态就添加动画
- (void)viewWillAppear:(BOOL)animated {
    if ([RadioPlay sharedRadioPlay].readyToPlay == YES) {
        [self.view addSubview:self.view1];
        [self.view bringSubviewToFront:self.view1];
        [self.imageView1 startAnimating];
        [self.view1 addSubview:self.imageView1];
    }
}

// 手势的点击事件，返回播放页面
- (void)returnPlay {
    [self.navigationController presentViewController:[RadioPlay sharedRadioPlay].playRadioTVC animated:YES completion:nil];
}

// 设置 collectionView
- (void)setCollectionView {
    
    // 创建集合视图
    // 创建布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 15;
    flowLayout.minimumLineSpacing = 40;
    
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 15, 10, 15);
    
    // item 的宽度
    CGFloat itemWidth = (kWidth - 4 * 15) / 3.0;
    CGFloat itemHeight = itemWidth / 2.0 * 3.3;
    
    // item 的size
    flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
    
    // 滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    // 设置区头大小
    flowLayout.headerReferenceSize = CGSizeMake(0, 40);
    
    // 创建 collectionView 对象，并赋值布局
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    // 设置数据源的代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    // 注册单元格
    [self registerCellAndReusable];
    
    [self.view addSubview:self.collectionView];
    
}


// 注册单元格
- (void)registerCellAndReusable {
    
    [self.collectionView registerClass:[RadioCollectionViewCell class] forCellWithReuseIdentifier:@"collectionCell"];
    
    [self.collectionView registerClass:[RadioCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collectionHeader"];
    
}

// 分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [self.sectionTitleArr count];
}

// 分区中item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [[self.allArray objectAtIndex:section] count];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 加载 item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    RadioCollectionViewCell *radioCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
    NSArray *radioList = self.allArray[indexPath.section];
    radioCell.radioListModel = radioList[indexPath.item];
    return radioCell;
    
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    RadioCollectionReusableView *radioReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collectionHeader" forIndexPath:indexPath];
    radioReusableView.sectionTitle.text = self.sectionTitleArr[indexPath.section];
    
    radioReusableView.tag = indexPath.section;
    
    // 给区头添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(turnToSingleRadioListVC:)];
    
    [radioReusableView addGestureRecognizer:tap];
    
    return radioReusableView;
    
}

// 区头点击事件
- (void)turnToSingleRadioListVC:(id)sender {
    
    UITapGestureRecognizer *tapSender = (UITapGestureRecognizer *)sender;
    SingleRadioListTableViewController *singleRadioList = [[SingleRadioListTableViewController alloc] init];
    
    NSArray *array = self.allArray[tapSender.view.tag];
    RadioListModel *radio = array[0];
    singleRadioList.cid = radio.cid;
    singleRadioList.title = self.sectionTitleArr[tapSender.view.tag];
    
    [self.navigationController pushViewController:singleRadioList animated:YES];
    
}


// item 的点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *array = self.allArray[indexPath.section];
    RadioListModel *radio = array[indexPath.item];
    PlayRadioTableViewController *playRadioVC = [[PlayRadioTableViewController alloc] init];
    PlayRadioModel *playRadioModel = [RadioPlay sharedRadioPlay].radioListArray[0];
    
    if ([playRadioModel.title isEqualToString:radio.radio[@"title"]]) {
        [self.navigationController presentViewController:[RadioPlay sharedRadioPlay].playRadioTVC animated:YES completion:nil];
    }else {
        playRadioVC.tid = radio.tid;
        NSArray *arr = [self setDataWithTid:radio.tid];
        [RadioPlay sharedRadioPlay].radioListArray = arr;
        [RadioPlay sharedRadioPlay].item = 0;
        
        playRadioVC.allArray = (NSMutableArray *)arr;
        [self.navigationController presentViewController:playRadioVC animated:YES completion:nil];
    }
    
    
    
    
}

// 解析
- (NSArray *)setDataWithTid:(NSString *)tid {
    
    NSMutableArray *array = [NSMutableArray array];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:kDetailRadio,tid]];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    for (NSDictionary *dic in rootDic[tid]) {
        PlayRadioModel *playRadioModel = [[PlayRadioModel alloc] init];
        [playRadioModel setValuesForKeysWithDictionary:dic];
        [array addObject:playRadioModel];
    }
    
    return  array;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
